package com.mass.core.sys.user.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.mass.core.framework.aop.LogAop;
import com.mass.core.framework.interceptor.SessionListener;
import com.mass.core.socket.config.WebSocket;
import com.mass.core.sys.authority.services.SysAuthorityServices;
import com.mass.core.sys.role.model.SysRole;
import com.mass.core.sys.role.services.SysRoleServices;
import com.mass.core.sys.user.model.SysUser;
import com.mass.core.sys.user.services.SysUserServices;
import com.mass.core.token.JwtComponent;
import com.mass.core.utils.AjaxResponse;
import com.mass.core.utils.CodeUtil;
import com.mass.core.utils.CusAccessObjectUtil;
import com.mass.core.utils.DateUtils;

/**
 * 
 * @ProjectName:  [demo-ht] 
 * @Package:      [com.mass.core.sys.user.components.SignController.java]
 * @ClassName:    [SignController]   
 * @Description:  [登录]   
 * @Author:       [张双喜]   
 * @CreateDate:   [2018年5月27日 下午5:14:55]   
 * @UpdateUser:   [zsx]   
 * @UpdateDate:   [2018年5月27日 下午5:14:55]   
 * @Since         [JDK1.7]
 * @Version:      [v1.0]
 *
 */
@RestController
@RequestMapping("/sign")
public class SignController{

    private final static Logger LOGGER = LoggerFactory.getLogger(SignController.class);
    
    @Autowired
	private SysUserServices sysUserServices;   //注入用户接口
    
    @Autowired
    private SysRoleServices roleServices;	   //注入角色接口	
    
    @Autowired
    private SysAuthorityServices sysAuthorityServices; //注入权限接口 
    
    @Value("${ueditor.upload-path}")
    private String basePath;      //上传文件路径
    
    @Value("${server.context-path}")
	private String projectName;   //项目前缀
    
    @Autowired
    private JwtComponent jwtComponent;   //JWT  组件

    /**
     * 
    * @Title: getImageCodeMap
    * @Description: 获取验证码
    * @return AjaxResponse 返回类型   
    * @throws
     */
    @RequestMapping(value = "/getImageCodeMap",method = RequestMethod.GET)
    public AjaxResponse getImageCodeMap(HttpSession session){
    	Map<String,String> map = CodeUtil.getImageCodeMap(basePath.replaceAll("\\\\",""),projectName);
    	session.setAttribute("code", map.get("code"));
    	return AjaxResponse.success("ok",map);
    }
    
    /**
     * 系统用户登录
     *
     * @param session   当前会话
     * @return  登录结果
     */
    
    @LogAop(menuName="用户登录",operationDesc="登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public AjaxResponse in(HttpSession session, HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        try {
        	if(!ObjectUtils.isEmpty(code)){
        		String sessionCode = (String) session.getAttribute("code");
        		if(!code.equalsIgnoreCase(sessionCode)){
        			return AjaxResponse.error("验证码不正确！");
        		}
        	}
        	SysUser sysUser = sysUserServices.checkAccountIsExist(username);
        	if(ObjectUtils.isEmpty(sysUser)){
        		return AjaxResponse.error("用户名不存在！");
        	}else{
        		if(sysUser.getEnabled()!=null && sysUser.getEnabled()==1){
        			//登录
        			sysUser = sysUserServices.checkLogin(username, password);
        			if(!ObjectUtils.isEmpty(sysUser)){
        				if(sysUser.getaSingleLogin()!=null && sysUser.getaSingleLogin() == 1){//单一登录
        					SessionListener.addUserLoginNumber(sysUser.getAccount());
        					//获取存用户唯一标识
        					String userToken = SessionListener.getUserMap().get(sysUser.getAccount());
        					if(!ObjectUtils.isEmpty(userToken)){
        						AjaxResponse ajaxResponse = new AjaxResponse("2000", "用户已在其他设备上登录!", "用户已在其他设备上登录!");
        						WebSocket.sendMessage(ajaxResponse, userToken);
        					}
        					SessionListener.UserLoginNumber uli = SessionListener.getUserLoginNumber(sysUser.getAccount());
        					if(!ObjectUtils.isEmpty(uli) && uli.getLoginNuber()>5){
        						return AjaxResponse.success("2001", "登录频繁！", (System.currentTimeMillis()-uli.getLoginTime()));
        					}
        				}
        				//查询用户有哪些角色
        				List<SysRole> sysRoleList = roleServices.findRoleByUserId(sysUser.getId());
        				Map<Long,SysRole> mapRole = new HashMap<Long, SysRole>();
        				for(SysRole r:sysRoleList){
        					mapRole.put(r.getId(), r);
        				}
        				sysUser.setMapRole(mapRole);
        				sysUser.setSysRoleList(sysRoleList);
        				
        				//修改用户登录IP 时间
        				sysUser.setLastLoginIp(CusAccessObjectUtil.getIpAddress(request));
        				sysUser.setLastLoginTime(DateUtils.getDate());
        				sysUser.setNumberPasswordError(0);
        				sysUserServices.updateSysUser(sysUser,session);
        				
        				String jwtToken = jwtComponent.createJWT(sysUser.getAccount(),
        						sysUser.getId().toString(),
        						sysUser.getRoleId().toString());
        				String user_UUID =  UUID.randomUUID().toString().replaceAll("-",""); 
        				//添加登录用户
        				SessionListener.addUser(sysUser.getAccount(), user_UUID);
        				sysUser.setToken(jwtToken);
        				sysUser.setUUID(user_UUID);
        				session.setAttribute("sysUser", sysUser);
        				return AjaxResponse.success("登录成功！",user_UUID);
        			}else{
        				SysUser user = sysUserServices.checkAccountIsExist(username);
        				int errorNumber = user.getNumberPasswordError();
        				if(errorNumber < 5){
        					user.setNumberPasswordError((errorNumber+1));
        					sysUserServices.updateSysUserInfo(user);
        					return AjaxResponse.error("密码错误，还剩"+(5-errorNumber)+"次机会！");
        				}else{
        					user.setNumberPasswordError((errorNumber+1));
        					user.setEnabled(0);
        					sysUserServices.updateSysUserInfo(user);
        					return AjaxResponse.error("登录错误超过5次，用户已被禁用！");
        				}
        			}
        		}else{
        			return AjaxResponse.error("用户已被禁用！");
        		}
        	}
        } catch (Exception e) {
            LOGGER.error("login error!", e);
            return AjaxResponse.error("Login error!");
        }
        
    }

    @LogAop(menuName="用户注销",operationDesc="注销")
    @RequestMapping("/logout")
    public AjaxResponse logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
    	request.getSession().invalidate();
        return AjaxResponse.success("OK");
    }

    /**
     * 获取系统当前用户信息
     *
     * @param session   当前会话
     * @return  当前会话的用户信息
     */
    @RequestMapping("/getCurrentUserInfo")
    public AjaxResponse getCurrentUserInfo(HttpSession session) {
    	SysUser sysUser = (SysUser) session.getAttribute("sysUser");
    	SysUser user = sysUserServices.findSysUserByUserId(sysUser.getId());
    	sysUser.setOpenId(user.getOpenId());
    	sysUser.setTabCache(user.getTabCache());
    	sysUser.setTabRefresh(user.getTabRefresh());
    	sysUser.setaSingleLogin(user.getaSingleLogin());
    	sysUser.setLockScreen(user.getLockScreen());
    	sysUser.setNumberPasswordError(user.getNumberPasswordError());
    	sysUser.setAnnouncement(user.getAnnouncement());
        return AjaxResponse.success("OK",sysUser);
    }
}
